package com.tiancheng.onecode.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.tiancheng.onecode.exception.Asserts;
import com.tiancheng.onecode.service.WechatMiniAppService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Author: kellen
 * @Description:
 * @Date: create in 2024/10/23 10:39
 */
@Slf4j
@Service
public class WechatMiniAppServiceImpl implements WechatMiniAppService {

    @Resource
    private WxMaService wxMaService;

    @Override
    public WxMaJscode2SessionResult login(String appId, String code) {
        try {
            return wxMaService.getUserService().getSessionInfo(code);
        } catch (Exception e) {
            log.info("WechatMiniAppService.login fail. message={}", e.getMessage(), e);
            Asserts.fail("微信小程序登录失败!");
            return null;
        }
    }

    @Override
    public WxMaPhoneNumberInfo getPhone(String appId, String code) {
        try {
            return wxMaService.getUserService().getPhoneNoInfo(code);
        } catch (Exception e) {
            log.info("WechatMiniAppService.login fail. message={}", e.getMessage(), e);
            Asserts.fail("微信小程序获取授权手机号失败!");
            return null;
        }
    }

    @Override
    public void switchAppId(String appId) {
        if (!StringUtils.hasLength(appId) || !wxMaService.switchover(appId)) {
            log.error("WechatMiniAppService.switchAppId fail. 未找到对应appid={}的配置，请核实", appId);
            Asserts.fail("未配置对应appId!");
        }
    }
}
